<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>2_key的作用</title>
</head>

<body>

    <div id="test" />
    <script type="text/javascript"
        src="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/react/18.2.0/umd/react.production.min.js"></script>
    <script type="text/javascript"
        src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
    <script type="text/javascript"
        src="https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/babel-standalone/6.26.0/babel.min.js"></script>

    <script type="text/babel">
        class Person extends React.Component {
            state = {
                persons: [
                    { id: 1, name: '小张', age: 18 },
                    { id: 2, name: '小李', age: 19 },
                    { id: 3, name: '小王', age: 20 },
                ]
            }

            add = () => {
                const { persons } = this.state
                //alert(this.state.persons)
                const p = { id: persons.length + 1, name: '王虎', age: 22 }
                this.setState({ persons: [p, ...persons] })  // 数组中添加元素
            }

            // 使用index索引值做key,, 使用id(数据的唯一标识)作为key可以提高效率问题
            render() {
                return (
                    <div>
                        <h2>展示人员信息</h2>
                        <button onClick={this.add}>添加一下王虎</button>
                        <ul>
                            {
                                this.state.persons.map((person, index) => {
                                    return <li key={person.id}>{person.name}-{person.age}</li>
                                })
                            }
                        </ul>
                    </div>
                )
            }
        }
        ReactDOM.render(<Person />, document.getElementById("test"))
    </script>
</body>

</html>